#include <reg52.h>  // 包含51单片机寄存器定义头文件

// 延时函数，用于控制跑马灯的速度
void Delay(unsigned int t) {
    unsigned int i, j;
    for (i = t; i > 0; i--)
        for (j = 110; j > 0; j--);
}

// 模式1：单灯左右移动
void mode_single_shift() {
    unsigned char LED = 0x01;
    unsigned char dir = 1;
    
    while (1) {
        P1 = ~LED;
        
        if (dir) {
            LED <<= 1;
            if (LED == 0x80) dir = 0;
        } else {
            LED >>= 1;
            if (LED == 0x01) dir = 1;
        }
        
        Delay(300);
        
        // 检查是否需要切换模式
        if (P3_0 == 0) break;  // 如果P3.0按键被按下，退出当前模式
    }
}

// 模式2：双灯追逐
void mode_double_chase() {
    unsigned char LED = 0x03;  // 初始状态，两个相邻的LED亮
    unsigned char dir = 1;
    
    while (1) {
        P1 = ~LED;
        
        if (dir) {
            LED <<= 1;
            if (LED == 0xC0) dir = 0;
        } else {
            LED >>= 1;
            if (LED == 0x03) dir = 1;
        }
        
        Delay(200);
        
        if (P3_0 == 0) break;
    }
}

// 模式3：闪烁模式
void mode_blink() {
    unsigned int i;
    
    while (1) {
        // 全亮
        P1 = 0x00;
        Delay(200);
        
        // 全灭
        P1 = 0xFF;
        Delay(200);
        
        if (P3_0 == 0) break;
    }
}

// 模式4：流水灯
void mode_water_flow() {
    unsigned char pattern[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
    unsigned char i;
    
    while (1) {
        for (i = 0; i < 8; i++) {
            P1 = ~pattern[i];
            Delay(100);
            
            if (P3_0 == 0) break;
        }
        
        if (P3_0 == 0) break;
    }
}

void main() {
    unsigned char mode = 0;
    
    while (1) {
        switch (mode) {
            case 0:
                mode_single_shift();
                break;
            case 1:
                mode_double_chase();
                break;
            case 2:
                mode_blink();
                break;
            case 3:
                mode_water_flow();
                break;
        }
        
        // 切换模式
        mode = (mode + 1) % 4;
        
        // 按键消抖
        Delay(200);
        while (P3_0 == 0);  // 等待按键释放
        Delay(200);
    }
}